package org.example.authservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.authservice.mapper.RoleMapper;
import org.example.authservice.pojo.Role;
import org.example.authservice.pojo.UserRole;
import org.example.authservice.service.RoleRepository;
import org.example.authservice.service.RoleService;
import org.example.authservice.service.UserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 顾翔宇
 * @since 2024/12/16 11：34
 * @version 1.0
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleRepository roleRepository;
    @Resource
    private UserRoleService userRoleService;

    /**
     * 根据用户id获取角色
     *
     * @param id 用户id
     * @return 角色
     */
    @Override
    public List<Integer> getUserRoleById(Integer id) {
        return roleMapper.getUserRoleById(id);
    }

    /**
     * 根据权限id获取角色
     *
     * @param id 权限id
     * @return 角色
     */
    @Override
    public List<Integer> getPermissionRoleById(Integer id) {
        return roleMapper.getPermissionRoleById(id);
    }

    /**
     * 查找所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<Role> getAllRoles(){
        return roleRepository.findAll();
    }

    /**
     * 添加角色
     *
     * @param role 角色
     */
    @Override
    public void add(Role role) {
        String name=role.getName();
        String comment=role.getComment();
        roleMapper.addRole(name,comment);
    }

    /**
     * 根据id判断是否为默认角色
     *
     * @param id 用户id
     * @return 是否为默认角色
     */
    @Override
    public boolean isDefaultRole(Integer id) {
        Role role = baseMapper.selectById(id);
        return role != null && role.getIsDefault() == 0;
    }

    /**
     * 判断是否有用户绑定该角色
     *
     * @param id 用户id
     * @return 是否有用户绑定该角色
     */
    @Override
    public boolean hasUsersWithRole(Integer id) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getRoleId, id);
        return !userRoleService.list(queryWrapper).isEmpty();
    }
}